package com.xone.xapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class UserInfoUpdateActivity extends BasicActivity {
	protected final String TAG = UserInfoUpdateActivity.class.getSimpleName();
	protected Map<String, String> infoMap = new LinkedHashMap<String, String>();
    protected LinearLayout outerView;
    protected String id;
	@Override
	public String getHeaderTitle() {
		return "更新用户信息";
	}
	@Override
	public int getContentView() {
		return R.layout.user_info_update;
	}
	@Override
	public Context getContext() {
		return this;
	}
	public String getPostURL() {
		return "/login/updateJson.html";
	}
	/**
	 * 提交完成后的回调
	 */
	public void doPostFinish(JSONObject result) {
		hideProgress();
		if (null == result) {
			Toast.makeText(getContext(), "操作失败", Toast.LENGTH_SHORT).show();
			return;
		}
		String msg = "提交成功";
		JSONObject mapValue = JSONUtils.getJSONObjectForKey(result, "mapValue");
		if (mapValue.isNull("msg")) {
			Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
			this.finish();
			return;
		}
		msg = JSONUtils.getStringFromJSONObject(mapValue, "msg");
		Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
	}
	protected void onCreate(Bundle savedInstanceState) {
		Bundle bundle = this.getIntent().getExtras();
		super.onCreate(savedInstanceState);
		if (null != bundle) {
			id = bundle.getString("id");
			if (StringUtils.isBlank(id)) {
				Toast.makeText(this, "无关键性参数信息", Toast.LENGTH_SHORT).show();
				this.finish();
				return;
			}
		}
		infoMap.put("nickName", "昵称不能为空");
		infoMap.put("cellphone", "手机号码不能为空");
		infoMap.put("username", "用户名不能为空");
		infoMap.put("contactor", "");
		infoMap.put("qq", "");
		infoMap.put("email", "");
		infoMap.put("address", "");
		infoMap.put("password", "密码不能为空");
		infoMap.put("repassword", "确认密码不能为空");
		outerView = (LinearLayout)findViewById(R.id.user_info_update_details_zone);
		showProgress();
		new InitDataTask(this, outerView).execute(id);
		Button submit = (Button)findViewById(R.id.submit_update_user_info);
		submit.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onClick(final View v) {
				ContextUtils.confirm(getContext(), "确认更新用户信息？", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Map<String, String> value = checkAndGetValue(infoMap);
						if (value.isEmpty()) {
							return;
						}
						showProgress();
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						for (Map.Entry<String, String> info : value.entrySet()) {
							params.add(new BasicNameValuePair("person." + info.getKey(), info.getValue()));
						}
						params.add(new BasicNameValuePair("update", "update"));
						new PostDataTask(getContext(), v).execute(params);
					}
				});
			}
		});
	}
	
	protected boolean notPass(String value, String notice) {
		if (StringUtils.isBlank(value)) {
			Toast.makeText(getContext(), notice, Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}
	
	public Map<String, String> checkAndGetValue(Map<String, String> infoMap) {
		Map<String, String> valueMap = new HashMap<String, String>();
		for (Map.Entry<String, String> info : infoMap.entrySet()) {
			EditText editText = (EditText)findViewById(ContextUtils.getResourceId(getContext(), info.getKey(), "id"));
			String value = editText.getText().toString();
			if (StringUtils.isNotBlank(info.getValue()) && notPass(value, info.getValue())) {
				return Collections.emptyMap();
			}
			valueMap.put(info.getKey(), value);
		}
		return valueMap;
	}
	
	public class InitDataTask extends AsyncTask<String, Integer, JSONObject> {
		protected Context context;
		protected LinearLayout view;
		public InitDataTask(Context context, LinearLayout view) {
			this.context = context;
			this.view = view;
		}
		@Override
		protected JSONObject doInBackground(final String... params) {
			if (isCancelled()) {
				return null;
			}
			List<NameValuePair> reqparams = new ArrayList<NameValuePair>();
			reqparams.add(new BasicNameValuePair("person.username", params[0]));
			return HttpUtils.httpGet(Constants.APP_URL + "/login/indexUpdateJson.html", reqparams, 
					new HttpUtils.onGetSuccessListener<JSONObject>() {
						@Override
						public JSONObject onSuccess(int status, String result) {
							if (HttpUtils.SC_OK == status) {
								JSONObject jsonObject = JSONUtils.getJSONObjectFromString(result);
								JSONObject person = JSONUtils.getJSONObjectForKey(jsonObject, "person");
								return person;
							} else {
								Toast.makeText(context, "Status Code:" + status, Toast.LENGTH_SHORT).show();
							}
							return null;
						}
					}, context);
		}
		@Override
		protected void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
			if (null == result) {
				hideProgress();
				return;
			}
			JSONObject person = result;
			int childCount = view.getChildCount();
			for (int i = 0 ; i < childCount; i++) {
				View v = view.getChildAt(i);
				String tag = (String)v.getTag();
				if (v instanceof LinearLayout && null != tag) {
					String value = null;
					if (!person.isNull(tag)) {
						value = JSONUtils.getStringFromJSONObject(person, tag);
					}
					if (null != value) {
						EditText tv = (EditText)view.findViewById(context.getResources().getIdentifier(tag, "id", context.getPackageName()));
						if (null != tv) {
							tv.setText(value);
						}
					}
				}
			}
			hideProgress();
		}
	}
	
	public class PostDataTask extends AbstractPostDataTask {
		protected Context context;
		protected View view;
		public PostDataTask(Context context, View view) {
			super(context);
			this.view = view;
		}
		@Override
		public String getPostUrl() {
			return getPostURL();
		}
		@Override
		public void postFinish(JSONObject result) {
			this.view.setEnabled(true);
			if (null == result) {
				hideProgress();
				return;
			}
			doPostFinish(result);
		}
	}

}
